﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Diagnostics;
using System.Linq;
using System.Text;
using _4m.Utils;

namespace _4m.utils
{
    public class SQLiteUtils
    {
        public bool TestConnect(string connString)
        {
            bool flag = false;
            try
            {
                SQLiteConnection conn = new SQLiteConnection(connString);
                conn.Open();
                Debug.WriteLineIf(Constants.Debug, "SQLite connect OK");
                flag = true;
            }
            catch (Exception exception)
            {
                Debug.WriteLineIf(Constants.Debug, "SQLite connect fail: {0}", exception.Message);
            }
            return flag;
        }

        public int ExecuteUpdate(string sqlStr, string connStr)
        {
            int count = 0;
            using (SQLiteConnection conn = new SQLiteConnection(connStr))
            {
                conn.Open();
                SQLiteCommand comm = conn.CreateCommand();
                comm.CommandText = sqlStr;

                count = comm.ExecuteNonQuery();
            }
            return count;
        }

        public int ExecuteUpdate(string sqlStr, SQLiteParameter[] parameters, string connStr)
        {
            int count = 0;
            using (SQLiteConnection conn = new SQLiteConnection(connStr))
            {
                conn.Open();
                SQLiteCommand comm = conn.CreateCommand();
                comm.CommandText = sqlStr;
                comm.Parameters.Add(parameters);

                count = comm.ExecuteNonQuery();
            }
            return count;
        }

        public static void CreateDatabaseFile(string path)
        {
            Debug.WriteLineIf(Constants.Debug, string.Format("在{0} 创建数据库", path));
            SQLiteConnection.CreateFile(path);
        }

        public static string GetConnectionString(string path)
        {
            return GetConnectionString(path, null);
        }

        public static string GetConnectionString(string path, string password)
        {
            if (string.IsNullOrEmpty(password))
            {
                return string.Format("Data Source={0}", path);
            }
            else
            {
                return string.Format("Data Source={0};Password={1}", path, password);
            }
        }
    }
}
